package com.atguigu.flow.controller;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.commonutils.R;

import com.atguigu.flow.comm.CommJSON;
import com.atguigu.flow.config.TaxCloudConfig;
import com.atguigu.flow.entity.ParamBO;
import com.atguigu.flow.entity.vo.CurrentUser;
import com.atguigu.flow.entity.vo.Modal_username;
import com.atguigu.flow.entity.vo.TokenInfoBO;
import com.atguigu.flow.service.ItemsService;
import com.atguigu.flow.service.QuotationsLineService;
import com.atguigu.flow.service.SysApiService;
import com.atguigu.flow.utils.AttachmentSave;
import com.atguigu.flow.utils.RSAdemo;
import com.atguigu.flow.utils.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.xmlbeans.impl.jam.JSourcePosition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.List;

import static javax.crypto.Cipher.DECRYPT_MODE;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-03-02
 */
@Api(description="产品扫描管理")
@RestController
@RequestMapping("/itemsscan")
@CrossOrigin
public class ItemsController {
    @Autowired
    private  RedisTemplate<String, String> redisTemplate;


    @Autowired
    private
    ItemsService itemsService;
    @Autowired
    private AttachmentSave attachmentSave;
    @Autowired
    private
    TaxCloudConfig taxCloudConfig;
    @Autowired
    private
    QuotationsLineService quotationsLineService;

    final static String SLAT = "loie_api";

    @ApiOperation(value = "返回库存产品图片模块")
    @PostMapping("proudctimage/{itemno}")
    public
    R proudctimage(@PathVariable String itemno) throws Exception {
        JSONObject json=quotationsLineService.productimaglist(itemno);
        //return null;
        return R.ok().data(json);
    }


    @ApiOperation(value = "返回产品资料模块")
    @PostMapping("itemsshowlist/{modulename}/{recordid}/{username}")
    public
    R itemsshowlist(@PathVariable String modulename, @PathVariable String recordid,
                    @PathVariable String username) throws Exception {
        JSONObject json=itemsService.itemsshowlist(modulename,recordid,username);
      //return null;
       return R.ok().data(json);
    }

    @ApiOperation(value = "产品资料模块字段查询")
    @PostMapping("items_modeulelist")
    public
    CommJSON items_modeulelist(@RequestBody String msg, @CurrentUser TokenInfoBO tokenInfoBO) throws Exception {
        CommJSON commJson = new CommJSON();
        try {

        String aesSecureKey = redisTemplate.opsForValue().get(SecureUtil.MD5Encode(String.format("[DataCenter][secretKey][%s]",
                tokenInfoBO.getToken())));
        String mwMsg = SecureUtil.decryptAES(msg, aesSecureKey);
        Modal_username paramBO = JSONObject.parseObject(mwMsg, Modal_username.class);


        JSONObject json=itemsService.itemsshowlist(paramBO.getModulename(),
                paramBO.getRecordid(),paramBO.getUsername());
        //return null;
            commJson.setSuc();
            commJson.setData(SecureUtil.encryptAES(json.toJSONString(), aesSecureKey));
        } catch (Exception e) {
            e.printStackTrace();
            commJson.setErrorCode("0301");
            commJson.setErrorMessage("获取菜单异常，请刷新后重试");
            commJson.setError();
        }
        return commJson;
    }


    @ApiOperation(value = "返回附件base64")
    @PostMapping("attachmenttobase64/{parentid}/{recordid}/{filename}")
    public
    R attachmenttobase64(@PathVariable String parentid, @PathVariable String recordid,
                    String filename){
        JSONObject json=attachmentSave.attachmenttobase64(parentid,recordid,filename);
        //System.out.println(json);
        return R.ok().data(json);
    }
    @ApiOperation(value = "加密")
    @PostMapping("encryptRSA")
    public
    R encryptRSA(@RequestBody JSONObject json)throws Exception {
        String algorithm = "RSA";
        File directory = new File("service/service_flow/src/main/resources");
        String reportPath = directory.getCanonicalPath();

        //保存公钥和私钥 generateKeyToFile(algorithm, "a.pub", "a.pri");
//        // 读取私钥
        PrivateKey privateKey = RSAdemo.getPrivateKey(reportPath+taxCloudConfig.getPrivatkeypath(), algorithm);
        //System.out.println(privateKey);
        // 读取公钥key
        PublicKey publicKey = RSAdemo.getPublicKey(reportPath+taxCloudConfig.getPublickeypath(), algorithm);
        //System.out.println(publicKey);

        //用私钥加密
        System.out.println("---------用私钥加密，公钥解密--------");
        String s = RSAdemo.encryptRSA(algorithm, privateKey, json.toJSONString());
        return R.ok().data("encryptRSA",s);


    }
    @ApiOperation(value = "解密")
    @PostMapping("decryptRSA")
    public
    R decryptRSA(@RequestBody JSONObject json)throws Exception {
        String algorithm = "RSA";
        String pass=json.getString("data");
        File directory = new File("service/service_flow/src/main/resources");
        String reportPath = directory.getCanonicalPath();

        //保存公钥和私钥 generateKeyToFile(algorithm, "a.pub", "a.pri");
        System.out.println(pass);
//        // 读取私钥
        PrivateKey privateKey = RSAdemo.getPrivateKey(reportPath+taxCloudConfig.getPrivatkeypath(), algorithm);
        //System.out.println(privateKey);
        // 读取公钥key
        PublicKey publicKey = RSAdemo.getPublicKey(reportPath+taxCloudConfig.getPublickeypath(), algorithm);
        //System.out.println(publicKey);

        //用私钥加密
        System.out.println("---------用私钥加密，公钥解密--------");
        String s=RSAdemo.decryptRSA(algorithm, publicKey, pass);
//        Cipher cipher = Cipher.getInstance(algorithm);
//        cipher.init(DECRYPT_MODE, publicKey);
//
//        // 执行解密操作
//        String s= new String(RSAdemo.getMaxResultDecrypt(pass, cipher));

        return R.ok().data("decrypt",s);


    }


}